package langnstats.project.ParserTools;

import java.util.ArrayList;

public class ParseTree {

	public static String getFeature(String line){
		//System.out.println("inside getFeature "+ line );
		Node root = new Node(new ArrayList<Node>(), null, null);
		Node currentNode = root;
		String[] words = line.split("  *");
		for (int i=0; i< words.length; i++){

			if (words[i].startsWith("[")) {} //ignore the scores
			else if (words[i].equals("(")) {
				currentNode.addChild(new Node(new ArrayList<Node>(), "", currentNode));
				currentNode = currentNode.getLastChild();	
			}
			else if (words[i].equals(")")) {
				currentNode = currentNode.getParent();	
			}
			else {
			
				currentNode.setLabel(words[i]);
			}
		}

		boolean finished = false;
		currentNode = root;
		String feature1 ="";
		while (!finished) {
			feature1 += (currentNode.getLabel() + " ");
			currentNode = currentNode.getLastChild();
			if (currentNode ==  null ) finished = true;					
		}
		words = feature1.split(" ");
		feature1 = words[words.length-3]+" "+words[words.length-2]+" ";
		//System.out.println("feature1 = "+feature1);
		
		return feature1;
		
		/*currentNode = root;
		Node LastLeave = root.getLastLeave();

		String feature2 ="";
		try{
			feature2 += LastLeave.getNextLeave().getParent().getParent().getLabel()+" ";
			feature2 += LastLeave.getNextLeave().getParent().getLabel()+" ";
			feature2 += LastLeave.getParent().getParent().getLabel()+" ";
			feature2 += LastLeave.getParent().getLabel()+" ";
		}catch (NullPointerException e) {
			return feature1;
		}
		System.out.println("feature2 = "+feature2);
		//System.out.println( words[words.length-3]+" "+words[words.length-2]+" ");
		String feature3 = "";
		try {
			feature3 = LastLeave.getSecondNextLeave().getParent().getLabel()+" " + feature2;
			feature3 = LastLeave.getSecondNextLeave().getParent().getParent().getLabel()+" "+feature3;
			System.out.println("feature 3= "+feature3);
			return feature3;

		}
		catch (NullPointerException E){
			//when we don't have 3gram in the tree..
			return feature2;
		}*/
	}

	public static void main(String[] args){
		String text= "( ROOT  ( FRAG [26.616]    ( NP [24.966] ( DT [21.982] x ) ) ) )";
		System.out.println(getFeature(text));
	}
}
